package com.imddy.wakeonlan.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


@Service
public class WakeonlanService {
    private static final Logger log = LoggerFactory.getLogger(WakeonlanService.class);

    /**
     * Sends a "magic packet" to the specified MAC address.
     *
     * @param macAddress The MAC address of the target machine in the format xx:xx:xx:xx:xx:xx.
     * @param ipBroadcastAddress The broadcast IP address of the target machine's network.
     * @throws IOException If there is an error sending the packet.
     */
    public static void sendMagicPacket(String macAddress, String ipBroadcastAddress) throws IOException {
        byte[] macBytes = parseMacAddress(macAddress);
        byte[] data = createMagicPacket(macBytes);

        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipBroadcastAddress), 9);
        try (DatagramSocket socket = new DatagramSocket()) {
            socket.send(packet);
        }
    }

    private static byte[] parseMacAddress(String macAddress) {
        String[] octets = macAddress.split(":");
        byte[] bytes = new byte[6];
        for (int i = 0; i < octets.length; i++) {
            bytes[i] = (byte) Integer.parseInt(octets[i], 16);
        }
        return bytes;
    }

    private static byte[] createMagicPacket(byte[] macBytes) {
        byte[] data = new byte[102];
        // Fill the first 6 bytes with 0xFF
        for (int i = 0; i < 6; i++) {
            data[i] = (byte) 0xff;
        }
        // Repeat the MAC address 16 times
        for (int i = 6, j = 0; i < data.length; i++, j++) {
            if (j == macBytes.length) j = 0;
            data[i] = macBytes[j];
        }
        return data;
    }


    public static void main(String[] args) {
        try {
            sendMagicPacket("00:11:22:33:44:55", "192.168.1.255");
            System.out.println("Magic packet sent.");
            log.info("Magic packet sent.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}